/**
 * Created by xinxinran on 2018/1/22.
 */
'use strict';
const daoHelper = require('../dao');
let authObj = require('./auth'), appObj = {}, allAppPath;

function refreshAuth(){
    let adminDao = daoHelper.getDao('minidoc-interfaceAdmin');
    let newAppDict = {};

    allAppPath = [];
    return adminDao.getAllApps().then(allApps => {
        allApps.forEach(appInfo => {
            newAppDict[appInfo.pathName] = appInfo.toJSON();
            allAppPath.push(`/view-${appInfo.pathName}`, `/manage-${appInfo.pathName}`);
        });
        appObj = newAppDict;

        return adminDao.getAllUsers();
    }).then(allUsers => {
        let newUserAuthObj = {};
        allUsers.forEach(uInfo => {
            let userInfo = uInfo.toJSON(), authApps = {};
            if(userInfo.isAdmin){
                userInfo.auth = allAppPath;
            }else{
                userInfo.auth = (userInfo.auth || []).filter(p => ~allAppPath.indexOf(p));
            }

            userInfo.auth.forEach(a => {
                let appPathNameInfo = /^\/(?:view|manage)-([^/]+)/.exec(a),
                    appPathName = (appPathNameInfo || [])[1];
                if(newAppDict[appPathName]){
                    authApps[appPathName] = newAppDict[appPathName];
                }
            });
            userInfo.authApps = Object.keys(authApps).map(pn => authApps[pn]).sort((a1, a2) => a1.sortNum - a2.sortNum);
            newUserAuthObj[userInfo.userName] = userInfo;
        });

        authObj = newUserAuthObj;
    });
}

refreshAuth();

exports.getAuthObj = function(){
    return authObj;
};

exports.getAppObj = function(){
    return appObj;
};

exports.validPath = function(path){
    return !!~allAppPath.indexOf(path);
};

exports.refreshAuth = refreshAuth;